package com.ecoolex.cms.system.core.manager;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.ecoolex.cms.system.core.dao.VRSceneHotspotParamDAO;
import com.ecoolex.cms.system.entity.VRSceneHotspot;
import com.ecoolex.cms.system.entity.VRSceneHotspotParam;
import com.ecoolex.cms.system.entity.VRSceneHotspotParamExample;
import com.ecoolex.framework.common.util.BeanUtil;

@Service
public class VRSceneHotspotParamManager {
	@Autowired
	private VRSceneHotspotParamDAO dao;

	public List<VRSceneHotspotParam> queryByHotspot(Integer hotspotId) {
		VRSceneHotspotParamExample example = new VRSceneHotspotParamExample();
		example.createCriteria().andHotspotIdEqualTo(hotspotId).andDeletedEqualTo(VRSceneHotspotParam.NOT_DELETED);
		return dao.selectByExample(example);
	}

	public Boolean add(VRSceneHotspot hotspot, List<VRSceneHotspotParam> paramList, String createUser) {
		paramList.forEach(param -> {
			param.setHotspotId(hotspot.getHotspotId());
			param.setDeleted(VRSceneHotspotParam.NOT_DELETED);
			param.setCreateUser(createUser);
			param.setCreateTime(Date.from(Instant.now()));
			param.setUpdateUser(createUser);
			param.setUpdateTime(Date.from(Instant.now()));

			dao.insert(param);
		});
		return true;
	}

	public Boolean edit(VRSceneHotspot hotspot, List<VRSceneHotspotParam> paramList, String updateUser) {
		Map<Integer, VRSceneHotspotParam> oldMap = queryByHotspot(hotspot.getHotspotId()).stream()
				.collect(Collectors.toMap(VRSceneHotspotParam::getParamId, self -> self));

		List<VRSceneHotspotParam> insertList = Lists.newArrayList();
		paramList.forEach(param -> {
			if (param.getParamId() == null || !oldMap.containsKey(param.getParamId())) {
				// 添加
				insertList.add(param);
			} else {
				// 修改
				VRSceneHotspotParam old = oldMap.get(param.getParamId());
				old.setUpdateUser(updateUser);
				old.setUpdateTime(Date.from(Instant.now()));
				BeanUtil.copy(param, old, "paramId", "hotspotId", "deleted", "createUser", "createTime", "updateUser",
						"updateTime");
				dao.updateByPrimaryKey(old);
				oldMap.remove(param.getParamId());
			}
		});

		// 添加新的
		add(hotspot, insertList, updateUser);
		// 删除
		oldMap.values().forEach(param -> {
			param.setDeleted(VRSceneHotspotParam.IS_DELETED);
			param.setUpdateUser(updateUser);
			param.setUpdateTime(Date.from(Instant.now()));
			dao.updateByPrimaryKey(param);
		});
		return true;
	}
}